package com.web.core.base.util;

import java.text.SimpleDateFormat;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.blue.core.dict.SeqType;
import com.web.core.base.model.Sequence;
import com.web.core.base.service.SequenceService;

/**
 * 生成序列工具类
 * 
 * @author zhengj
 * @since 2014-5-1 1.0
 */
@Component
public class SequenceUtil
{
	@Resource
	private SequenceService sequenceService; 
	
	public SequenceUtil()
	{
	}
	
	/**
	 * 返回当前序列
	 * 
	 * @param code 序列代码
	 * @return 当前序列
	 * @throws SequenceException 不存在序列时抛出
	 */
	public String nextVal(String code)
	{
		Sequence seq = sequenceService.getByCode(code);
		
		StringBuilder val = new StringBuilder(20);
		if (seq.getPrefix() != null && !seq.getPrefix().equals("")) // 前缀
			val.append(seq.getPrefix());
		if (seq.getType() == SeqType.NORMAL) // 普通
		{
			val.append(StringUtils.leftPad(String.valueOf(seq.getVal()), seq.getLength(), "0"));
		}
		else // 时间
		{
			SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
			val.append(f.format(seq.getDate()));
			val.append(StringUtils.leftPad(String.valueOf(seq.getVal()), seq.getLength() - 8, "0"));
		}
		if (seq.getSuffix() != null && !seq.getSuffix().equals("")) // 后缀
			val.append(seq.getSuffix());
		return val.toString();
	}
	
	
}
